//
//  ViewController.swift
//  LocalMusicPlayer
//
//  Created by darren on 16/9/21.
//  Copyright © 2016年 darren. All rights reserved.
//

import UIKit
import AVFoundation
import GoogleMobileAds
import FreeStreamer


class ViewController: UIViewController {
    /**进度条*/
    @IBOutlet weak var slideView: UISlider!
    /**底部的背景*/
    @IBOutlet weak var bottomImageView: UIImageView!
    /**毛玻璃*/
    @IBOutlet weak var toolBar: UIToolbar!
    /**转动图片*/
    @IBOutlet weak var iconView: UIImageView!
    /**歌词的ScrollView*/
    @IBOutlet weak var lrcScrollView: UIScrollView!
    @IBOutlet weak var rotationBottomView: UIView!
    /**播放暂停按钮*/
    @IBOutlet weak var playerBtn: UIButton!
    /**播放时间*/
    @IBOutlet weak var timerBeginLable: UILabel!
    /**总时间*/
    @IBOutlet weak var timerEndLable: UILabel!
    /**歌词lable*/
    @IBOutlet weak var lrcLable: CLLrcLable!
    /**歌曲信息*/
    @IBOutlet weak var singerlable: UILabel!
    /**展示广告的view*/
    @IBOutlet weak var BannerView: GADBannerView!
    /**展示歌词的tableView*/
    @IBOutlet weak var LrcTableView: UITableView!
    /**模型数组*/
    fileprivate lazy var musicArr:Array<musicModel> = []
    @IBOutlet weak var bgView: UIView!
    /**进度条计时器*/
    fileprivate var timerSlide: Timer?
    /**歌词数组*/
    var lrcArr = [String]()
    /**歌词时间数组*/
    var lycTimerArr = [String]()
    /**歌词定时器*/
    fileprivate var lrcTimer = CADisplayLink()
    /**当前行*/
    var currentIndex = 0
    /**底部的小图片*/
    @IBOutlet weak var smallIconView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.LrcTableView.delegate = self
        self.LrcTableView.dataSource = self
        self.setupNet()
        self.lrcLable.preferredMaxLayoutWidth = APPW
        self.lrcLable.adjustsFontSizeToFitWidth = true
        self.lrcLable.minimumScaleFactor = 0.1
        self.slideView.setThumbImage(UIImage(named: "slider"), for:UIControlState())
        
        // 90秒切换
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3*Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            self.view.insertSubview(self.toolBar, belowSubview: self.iconView)
            self.bgView.isHidden = false
            self.iconView.isHidden = true
            self.smallIconView.isHidden = false
        }
        
        // 监听状态，播放完成后自动播放下一首
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.myMovieFinishedCallback), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: MusicOperationTool.shareInstance.tool.player?.currentItem)
        
        // 内置广告
        BannerView.adUnitID = "ca-app-pub-9560168446225746/6660140111"
        BannerView.rootViewController = self
        let request:GADRequest = GADRequest()
        request.testDevices = [""]
        BannerView.load(request)
        
        self.iconView.isHidden = true
        self.smallIconView.isHidden = true
        
        // 延时设置，不然得不到真实地宽度
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            if self.iconView.cl_width*0.5>60 {
                CLViewsBorder(self.iconView, borderWidth: 0, borderColor: CoustomColor(0, g: 0, b: 0, a: 0.7), cornerRadius: self.iconView.cl_width*0.5)
                self.iconView.isHidden = false
            }
            CLViewsBorder(self.smallIconView, borderWidth: 0, borderColor: CoustomColor(0, g: 0, b: 0, a: 0.7), cornerRadius: 25)

            // 刚进入程序就播放
            if MusicOperationTool.shareInstance.musicMs.count>0 {
                self.playerBtn.isSelected = true
                self.clickPlatOrPauseBtn()
            }
        }
        
        // 点击了列表的歌曲
        CLNotificationCenter.addObserver(self, selector: #selector(updataMusicInfo), name: NSNotification.Name(rawValue: "clickMusicListItem"), object: nil)
        // 监听到播放完成，自动进入下一首
        CLNotificationCenter.addObserver(self, selector: #selector(stopPlayMusicAutoNext), name: NSNotification.Name(rawValue: "stopPlayAutoNext"), object: nil)

    }
    /**更新歌曲的信息*/
    func updataMusicInfo(){
        self.updateMusicLrcInfo()
        self.updataInfo()
    }
    func myMovieFinishedCallback(){
        self.clickNextBtn()
    }
    func stopPlayMusicAutoNext(){
        self.clickNextBtn()
    }
    
    override var prefersStatusBarHidden : Bool {
        return true;
    }
    
    @IBAction func clickCiBtn() {
        let lrcVC = SongViewController()
        self.present(lrcVC, animated: true, completion: nil)
    }
    @IBAction func clickListbtn() {
        let lrcVC = MusicListViewController()
        self.present(lrcVC, animated: true, completion: nil)
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }

    //MARK:- 开始或暂停
    @IBAction func clickPlatOrPauseBtn() {
        playerBtn.isSelected = !playerBtn.isSelected
        
        if playerBtn.isSelected {
            MusicOperationTool.shareInstance.pauseCurrentMusic()
            self.stopTimer()
            self.iconView.layer.pauseAnimate()
            self.stopIconRotion()
        } else {
            if MusicOperationTool.shareInstance.tool.musicState==FSAudioStreamState.fsAudioStreamPaused {
                MusicOperationTool.shareInstance.pauseCurrentMusic()
            } else {
                MusicOperationTool.shareInstance.playCurrentMusic()
            }
            // 转动头像
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
                MusicOperationTool.shareInstance.iconRotation(self.iconView,duration: 20)
                self.iconRotation()
            }
            self.startTimer()
            self.updataInfo()
            self.setupLrcArr(MusicOperationTool.shareInstance.currentModel)
        }

    }
    //MARK:- 下一首
    @IBAction func clickNextBtn() {
        MusicOperationTool.shareInstance.nextMusic()
        self.NextCommonMethod()
    }
    //MARK:- 上一首
    @IBAction func clickPreBtn() {
        MusicOperationTool.shareInstance.preMusic()
        self.NextCommonMethod()
    }
    func NextCommonMethod(){
        self.iconView.layer.resumeAnimate()
        self.stopIconRotion()
        MusicOperationTool.shareInstance.stopIconRotion(self.iconView)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            MusicOperationTool.shareInstance.iconRotation(self.iconView,duration: 20)
            self.iconRotation()
        }
        if self.playerBtn.isSelected {
            self.playerBtn.isSelected = false
        }
        
        // 更新歌曲歌词信息
        self.updateMusicLrcInfo()
        
        self.updataInfo()
    }
    // 更新歌曲歌词信息
    func updateMusicLrcInfo(){
        self.lrcArr.removeAll()
        self.lycTimerArr.removeAll()

        self.lrcLable.text = ""
        self.LrcTableView.reloadData()
        self.currentIndex = 0
        // 开启歌词的定时器
        self.startLrcTime()
        self.setupLrcArr(MusicOperationTool.shareInstance.currentModel)
        self.LrcTableView.reloadData()
    }
    
    /**启动定时器 更新进度*/
    func startTimer(){
        timerSlide = nil
        
        timerSlide = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(music), userInfo: nil, repeats: true)
        timerSlide?.fire()
    }
    /**关闭定时器*/
    func stopTimer(){
        if let _ = timerSlide?.isValid {
            timerSlide?.invalidate()
            timerSlide = nil
        }
    }
    /**启动定时器后每隔一段时间来到这个方法*/
    func music(){
        let musicInfoModel = MusicOperationTool.shareInstance.getMusicMessageModel() as MusicMessageModel
        self.slideView.value = Float(musicInfoModel.costTime)/Float(musicInfoModel.totalTime)
        
        // 当前时间
        let minute:Int = Int(musicInfoModel.costTime) / 60;
        let second:Int = Int(musicInfoModel.costTime) % 60;
        let currentTimeStr = String(format: "%02d:%02d",arguments:[minute,second])
        self.timerBeginLable.text = currentTimeStr
    }
    /**更新歌曲信息*/
    func updataInfo(){
        let model = MusicOperationTool.shareInstance.currentModel as musicModel
        self.singerlable.text = model.Title
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            let musicInfoModel = MusicOperationTool.shareInstance.getMusicMessageModel() as MusicMessageModel
            let totalT:Float = Float(musicInfoModel.totalTime)
            let minute:Int = Int(totalT) / 60;
            let second:Int = Int(totalT) % 60;
            let totalTimeStr = String(format: "%02d:%02d",arguments:[minute,second])
            self.timerEndLable.text = totalTimeStr
        }
        
    }

    /**快进快退*/
    @IBAction func clickSliderView(_ sender: AnyObject) {
        
        let musicInfoModel = MusicOperationTool.shareInstance.getMusicMessageModel() as MusicMessageModel
        let dur:Float = Float(musicInfoModel.totalTime)
        
        let value = self.slideView.value
        
        let timer:Float = value*dur
        
        var position = FSStreamPosition()
        position.minute = uint(timer/Float(60))
        position.second = uint(timer.truncatingRemainder(dividingBy: Float(60)))
        MusicOperationTool.shareInstance.tool.audioStream.seek(to: position)
    }
    
    func timeStringWithString(_ timeString:String)->Float{
        
        let min:Double = Double(timeString.components(separatedBy: ":")[0])!
        let range = NSMakeRange(3, 2)
        let second:Double = Double((timeString as NSString).substring(with: range))!
        let haomiao:Double = Double(timeString.components(separatedBy: ".")[1])!
        let timer1 = min*60
        let timer2 = haomiao*0.01
        return (Float)(timer1+timer2+second)
    }
    func getLabWidth(_ labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {
        let statusLabelText: NSString = labelStr as NSString
        let size = CGSize(width: APPW, height: height)
        let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
        return strSize.width
    }
    
    // 停止转动
    func stopIconRotion(){
        self.smallIconView.layer.removeAllAnimations()
    }
    // 开始转动
    func iconRotation(){
        let rotation = CABasicAnimation()
        rotation.duration = 10
        rotation.isRemovedOnCompletion = false
        rotation.repeatCount = MAXFLOAT
        rotation.keyPath = "transform.rotation.z"
        rotation.toValue = (M_PI*2)
        rotation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
        self.smallIconView.layer.add(rotation, forKey: nil)
    }
}
//MARK: - 歌词的解析
extension ViewController{
    func setupLrcArr(_ model:musicModel) {
        let lrcTool = LrcTools()
        let dataArray = lrcTool.setupLrcArrayAndLtrTimerArr(model: model)
        self.lrcArr = dataArray[0] as! [String]
        self.lycTimerArr = dataArray[1] as! [String]
        // 开启歌词的定时器
        self.startLrcTime()
        self.LrcTableView.reloadData()
    }

    //开启歌词定时器
    fileprivate func startLrcTime(){
        
        lrcTimer = CADisplayLink.init(target: self, selector: #selector(ViewController.updataLrc))
        lrcTimer.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
    }
    fileprivate func stopLrcTime(){
        self.startLrcTime()
        lrcTimer.invalidate()
    }
    @objc fileprivate func updataLrc(){
        let musicInfoModel = MusicOperationTool.shareInstance.getMusicMessageModel() as MusicMessageModel
        let dur:Float = Float(musicInfoModel.totalTime)
        let currTimer = MusicOperationTool.shareInstance.tool.audioStream.currentTimePlayed.position*dur
        self.setcurrentTime(currTimer)
    }
    
    fileprivate func setcurrentTime(_ currentTime:Float){
        let currentTime = currentTime
        // 当前播放的时间  4.467947662
        let minute:Int = Int(currentTime) / 60;
        let second:Int = Int(currentTime) % 60;
        let msecond:Int = Int(currentTime*100) - Int(currentTime)*100
        let currentTimeStr = String(format: "%02d:%02d.%02d",arguments:[minute,second,msecond])
        
        let currentShijian = self.timeStringWithString(currentTimeStr)
        
        let count = lycTimerArr.count
        for index in 0..<count {
            // 时间数组中每行的时间
            let currentLineTime:String = lycTimerArr[index]
            
            // 下一行的时间
            var nextLineTime = String()
            let nextIdx = index + 1
            var nextLineTimeDoubla:Float = 0
            
            if nextIdx < lycTimerArr.count {
                nextLineTime = lycTimerArr[nextIdx]
                nextLineTimeDoubla = self.timeStringWithString(nextLineTime)
            }
            if currentIndex == index {
                // 拿到当期位置的cell
                let indexPath = IndexPath.init(item: currentIndex, section: 0)
                let cell = self.LrcTableView.cellForRow(at: indexPath) as? MyLrcTableViewCell
                
                let currentLineStr:String = lycTimerArr[currentIndex]
                let currentLineTimer = self.timeStringWithString(currentLineStr)
                
                // 更新进度
                let progress = (currentShijian-currentLineTimer)/(nextLineTimeDoubla-currentLineTimer)
                cell?.cellprogress = CGFloat(progress)
                lrcLable.progress = CGFloat(progress)
            }
            
            // 控制屏幕旋转造成的位置偏移现象
            let indexPath1 = IndexPath.init(item: currentIndex, section: 0)
            let indexPath2 = IndexPath.init(item: currentIndex-1, section: 0)
            let indexPath3 = IndexPath.init(item: currentIndex+1, section: 0)
            let cell1 = self.LrcTableView.cellForRow(at: indexPath1) as? MyLrcTableViewCell
            let cell2 = self.LrcTableView.cellForRow(at: indexPath2) as? MyLrcTableViewCell
            let cell3 = self.LrcTableView.cellForRow(at: indexPath3) as? MyLrcTableViewCell
            cell1?.lrcLable.cl_centerX = self.LrcTableView.cl_centerX
            cell2?.lrcLable.cl_centerX = self.LrcTableView.cl_centerX
            cell3?.lrcLable.cl_centerX = self.LrcTableView.cl_centerX
            lrcLable.cl_centerX = self.view.cl_centerX

            if (currentTimeStr.compare(currentLineTime)==ComparisonResult.orderedAscending)==false && currentTimeStr.compare(nextLineTime)==ComparisonResult.orderedAscending && (currentIndex==index)==false {
                // 刷新tableView
                let reloadRows = [IndexPath.init(row: currentIndex, section: 0),IndexPath.init(row: index, section: 0)]
                
                currentIndex = index
                LrcTableView.reloadRows(at: reloadRows, with: .none)
                let indexPath = IndexPath.init(row: index, section: 0)
                LrcTableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            }
        }
    }

}
//MARK: - 解析数据都在这里
extension ViewController{
    fileprivate func setupNet(){
        MusicDataTool.getMusicData { (modelArr:Array<musicModel>) in
            self.musicArr = modelArr
        }
        // 将解析的数组 赋值给播放的工具类
        MusicOperationTool.shareInstance.musicMs = musicArr
    }
}
//MARK: - UITableViewDelegate，UITableViewDataSource
extension ViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lrcArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let ID = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = MyLrcTableViewCell(style: .default, reuseIdentifier: ID)
        }
        (cell as! MyLrcTableViewCell).selectionStyle = .none
        cell?.backgroundColor = UIColor.clear
        (cell as! MyLrcTableViewCell).lrcLable.text = lrcArr[(indexPath as NSIndexPath).row]
        
        (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.LrcTableView.cl_centerX
        
        if(self.currentIndex == (indexPath as NSIndexPath).row){
            (cell as! MyLrcTableViewCell).lrcLable.font = UIFont.systemFont(ofSize: 25)
            let str = (cell as! MyLrcTableViewCell).lrcLable.text
            let lableW = self.getLabWidth(str!, font: UIFont.systemFont(ofSize: 25), height: 30)
            (cell as! MyLrcTableViewCell).lrcLable.cl_width = lableW
            (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.LrcTableView.cl_centerX
            (cell as! MyLrcTableViewCell).lrcLable.textColor = UIColor.white
            lrcLable.text = str
            // 防止歌词过长
            if lrcLable.cl_width>APPW {
                lrcLable.cl_width = APPW
            }
            lrcLable.cl_centerX = self.view.cl_centerX
            lrcLable.adjustsFontSizeToFitWidth = true
            lrcLable.minimumScaleFactor = 0.1
            (cell as! MyLrcTableViewCell).lrcLable.adjustsFontSizeToFitWidth = true
            (cell as! MyLrcTableViewCell).lrcLable.minimumScaleFactor = 0.1
        } else {
            (cell as! MyLrcTableViewCell).lrcLable.cl_width = APPW  // 防止cell宽度复用
            (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.LrcTableView.cl_centerX
            (cell as! MyLrcTableViewCell).cellprogress = 0
            (cell as! MyLrcTableViewCell).lrcLable.font = UIFont.systemFont(ofSize: 15)
            (cell as! MyLrcTableViewCell).lrcLable.textColor = UIColor.white
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        LrcTableView.scrollToRow(at: indexPath, at: .middle, animated: true)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //  当前行
        let scrllCurrentLine = Int(((scrollView.contentOffset.y+LrcTableView.cl_height*0.5)/40)+LrcTableView.cl_height*0.5/40)
        // 这个一行的时间
        if scrllCurrentLine<lycTimerArr.count{
            let scrllCurrentLineTimeStr:String = lycTimerArr[scrllCurrentLine]
            let scrllCurrentLineTime:Float = (Float)(self.timeStringWithString(scrllCurrentLineTimeStr))
            
            var position = FSStreamPosition()
            position.minute = uint(scrllCurrentLineTime/Float(60))
            position.second = uint(scrllCurrentLineTime.truncatingRemainder(dividingBy: Float(60)))
            MusicOperationTool.shareInstance.tool.audioStream.seek(to: position)
            
            self.setcurrentTime((Float)(scrllCurrentLineTime))
        }
    }
}
extension ViewController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
    }
}
